package com.woniuxy.third.controller;

import com.woniuxy.third.entity.Chapter;
import com.woniuxy.third.entity.Course;
import com.woniuxy.third.entity.Order;
import com.woniuxy.third.entity.Sale;
import com.woniuxy.third.mapper.SaleMapper;
import com.woniuxy.third.result.ResponseResult;
import com.woniuxy.third.service.CourseService;
import com.woniuxy.third.service.OrderService;
import com.woniuxy.third.service.SaleService;
import com.woniuxy.third.service.UserService;
import com.woniuxy.third.utils.GetUserUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Author: yangtao
 *
 * @date 2021/7/20 17:38 @Version 1.0
 */
@RestController
@RequestMapping("/order")
public class OrderController {
  @Resource
  private OrderService orderService;
  @Resource
  private CourseService courseService;
  @Resource
  private UserService userService;
  @Resource
  private SaleService saleService;

  @GetMapping("/findAll")
  @ApiOperation(value = "查询订单", notes = "返回所有订单信息")
  public ResponseResult<List<Order>> findAll() {
    List<Order> orders = orderService.findAll();
    if (orders != null) {
      return new ResponseResult<>(200, "查询成功", orders);
    } else {
      return new ResponseResult<>(500, "无数据", orders);
    }
  }

  @GetMapping("/findallbyid")
  @ApiOperation(value = "查询订单", notes = "返回所有订单信息")
  public ResponseResult<List<Order>> findAll(HttpServletRequest request) {
    int id = GetUserUtil.getUser(request).getId();
    List<Order> orders = orderService.findAllByid(id);
    for (Order order:orders) {
      Course course = order.getCourse();
      List<Chapter> chapters = courseService.findChaptersByCourseId(course.getId());
      course.setChapters(chapters);
    }
    if (orders != null) {
      return new ResponseResult<>(200, "查询成功", orders);
    } else {
      return new ResponseResult<>(500, "无数据", orders);
    }
  }
  @Transactional
  @PostMapping("/addOrder")
  @ApiOperation(value = "添加订单(未支付状态)", notes = "返回是否添加成功")
  @ApiImplicitParam(paramType="query",name="cid",value="课程id",required=true)
  public ResponseResult<Order> addOrder(int cid,HttpServletRequest request) {
    /*int id = GetUserUtil.getUser(request).getId();*/
    Order order = new Order();
    order.setOrdernum(UUID.randomUUID().toString().replace("-", ""));
    order.setStatus(0).setUid(1002).setTime(new Date()).setCid(cid);
    int i=orderService.addOrder(order);
    if (i==1){
      return new ResponseResult<>(200, "添加成功", order);
    }
    return new ResponseResult<>(500, "添加失败", order);
  }
  @Transactional
  @PutMapping("/orderPaid")
  @ApiOperation(value = "修改订单信息为已支付，status值修改为1", notes = "返回所有订单信息")
  @ApiImplicitParams({
          @ApiImplicitParam(
                  paramType="query",name="id",value="订单id",
                  dataType="Integer",required=true),
          @ApiImplicitParam(
                  paramType="query",name="cid",value="商品id",
                  dataType="Integer",required=true)
  })
  public ResponseResult<String> orderPaid(int id,int cid,HttpServletRequest request){
    /*int uid = GetUserUtil.getUser(request).getId();*/
    int uid=1002;
    Order order=orderService.findByoid(id);
    if (order.getStatus()==1){
      return new ResponseResult<>(500, "订单已支付", null);
    }
    int i=orderService.orderstatus(id,1);
    if (i==1){
      Course course = courseService.findCourseByid(cid);
      BigDecimal price = course.getPrice();
      if (course != null) {
        if(price.compareTo(BigDecimal.ZERO)==0){
          return new ResponseResult<>(200, "购买成功", null);
        }else {
          BigDecimal balance = userService.findById(uid).getBalance();
          if (balance.compareTo(price)==-1){
            return new ResponseResult<>(500, "余额不足", null);
          }
          BigDecimal subtract = balance.subtract(price);
          int i1 = userService.updateBalance(uid, subtract);
          int teacherid = course.getTeacherid();
          BigDecimal balance1 = userService.findById(teacherid).getBalance();
          BigDecimal add = balance1.add(price);
          int i2 = userService.updateBalance(teacherid,add);
          order=orderService.findByoid(id);
          order.setTime(new Date()).setUid(course.getTeacherid());
          if(i1==1&&i2==1){
            saleService.addSale(order);
            return new ResponseResult<>(200, "购买成功", null);
          }
          return new ResponseResult<>(500, "购买失败", null);
        }
      }
      return new ResponseResult<>(500, "购买失败", null);
    }
    return new ResponseResult<>(500, "修改失败", null);
  }

  @Transactional
  @GetMapping("/orderCancel")
  @ApiOperation(value = "修改订单信息为已取消，status值修改为2", notes = "返回所有订单信息")
  @ApiImplicitParams({
          @ApiImplicitParam(
                  paramType="query",name="id",value="订单id",
                  dataType="Integer",required=true),
  })
  public ResponseResult<String> orderCancel(int id,HttpServletRequest request){
    int i=orderService.orderstatus(id,2);
    return new ResponseResult<>(200, "修改成功", null);
  }


}
